package com.tcm.ucenter.web.controller;

import cn.hutool.core.date.DateUtil;
import com.base.core.exception.ServiceException;
import com.base.core.lang.StringUtils;
import com.base.core.pager.PageBean;
import com.base.core.utils.R;
import com.tcm.ucenter.domain.enums.AccountTypeEnum;
import com.tcm.ucenter.service.UserAccountLogService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/ucenter/point/log")
public class UserPointLogController {

    @DubboReference(version = "0.0.1-alpha", timeout = 3000, check = false, retries = 3)
    UserAccountLogService userPointLogService;

    /**
     * 根据id获取但条数据
     *
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/view")
    public R view(@RequestParam("id") Long id) throws Exception {
        return R.success(userPointLogService.findById(id));
    }

    /**
     * 分页
     *
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @GetMapping("/list/page")
    public R listPointLogPage(@RequestParam("userId") Long userId,
                           @RequestParam(defaultValue = "1") Long page,
                           @RequestParam(defaultValue = "10") Long pagesize) {
        PageBean listBean = userPointLogService.listPageByUserId(userId, AccountTypeEnum.POINT.value(), page, pagesize);
        return R.success(listBean);
    }

    /**
     * 按时间分页
     *
     * @param
     * @return
     */
    @GetMapping("/list/page/date")
    public R listPointLogPageByDate(@RequestParam("userId") Long userId,
                            @RequestParam(defaultValue = "") String startTime,
                            @RequestParam(defaultValue = "") String endTime,
                            @RequestParam(defaultValue = "1") Long page,
                            @RequestParam(defaultValue = "10") Long pagesize) {
        Date startDate = null, endDate = null;
        if (StringUtils.isNotEmpty(startTime)){
            startDate = DateUtil.parseDate(startTime);
        }
        if (StringUtils.isNotEmpty(startTime)){
            endDate = DateUtil.parseDate(endTime);
        }
        PageBean listBean;
        try {
            listBean = userPointLogService.listPageByDate(userId, AccountTypeEnum.POINT.value(), startDate, endDate, page, pagesize);
        } catch (ServiceException e) {
            return R.fail(e.getResult().getCode(), e.getMessage());
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.success(listBean);
    }

}
